<template>
  <view class="page-container">
    <GlobalTopBar ref="topBarRef" class="topbars fixed" :isLeft="true">
      <template #title><text>招募师傅</text></template>
    </GlobalTopBar>
    <GlobalTopBar ref="topBarRef" :isLeft="true"> </GlobalTopBar>
    <view class="page_content">
      <template v-if="store.workerData?.status === 1">
        <view class="shbox flex_center">
          <image
            class="sh_img"
            :src="`${store.imgDomain}master_1.png`"
            mode="scaleToFill"
          />
          <text class="sh_text">等待审核</text>
          <view class="bm_text"
            >你的报名已提交，审核约需1-2个工作日，请等待审核。期间客服可能会联系你核实身份，请保持手机畅通。</view
          >
        </view>
        <!-- 文字 -->
        <view class="btext">
          <image :src="`${store.imgDomain}my_text2.png`" mode="scaleToFill" />
        </view>
      </template>
      <template v-else>
        <image
          class="hztopimg"
          :src="`${store.imgDomain}my_sf1.png`"
          mode="widthFix"
        />
        <!-- 相关信息 -->
        <view class="forms">
          <view class="formsbox">
            <view
              class="wtf_box flex_center"
              v-if="store.workerData?.status === 3"
            >
              <view class="flex" style="margin-bottom: 20rpx"
                ><image
                  class="qy_1_img"
                  :src="`${store.imgDomain}qy_1.png`"
                  mode="widthFix"
                />
                <text class="t1">审核未通过</text>
              </view>

              <view class="t2">您提交的资料存在以下问题：</view>
              <view class="t3">
                <text style="color: #ff2e00">{{
                  store.workerData?.examine_remark
                }}</text
                >,请修改后再次提交
              </view>
            </view>
            <view class="titles">
              <image :src="`${store.imgDomain}hz_3.png`" mode="scaleToFill" />
              申请服务人员
            </view>
            <!-- b -->
            <view class="jdlines flex">
              <view class="linredio" :class="{ ac: !store.workerData?.status }">
                <text>报名加入</text>
              </view>
              <view class="line"></view>
              <view
                class="linredio"
                :class="{ ac: store.workerData?.status === 3 }"
              >
                <text>后台审核</text></view
              >
              <view class="line"></view>
              <view class="linredio"> <text>认证签约</text></view>
            </view>
            <!-- 填写内容 -->
            <view class="form_item border_b">
              <view class="label">头像：</view>
              <button
                class="avatar-btn"
                open-type="chooseAvatar"
                @chooseavatar="onChooseAvatar"
              >
                <image
                  class="avatar"
                  :src="fromDttas.headimg || `${store.imgDomain}my_hade.png`"
                  mode="aspectFit"
                ></image>
              </button>
            </view>
            <view class="form_item border_b">
              <view class="label">姓名：</view>
              <input
                class="inps"
                v-model="fromDttas.worker_name"
                type="text"
                placeholder="请输入姓名"
              />
            </view>
            <view class="form_item border_b">
              <view class="label">联系电话：</view>
              <input
                class="inps"
                v-model="fromDttas.phone"
                type="number"
                placeholder="请输入联系电话"
              />
            </view>
            <view class="form_item border_b">
              <view class="label">服务类型：</view>
              <picker
                @change="bindPickerChange"
                :range="selectList"
                range-key="goods_category_title"
                style="flex: 1"
              >
                <view class="select">
                  <input
                    :value="type_title"
                    class="inps"
                    type="text"
                    disabled
                    placeholder="请选择服务类型"
                  />
                  <uni-icons type="right" size="18"></uni-icons>
                </view>
              </picker>
            </view>
            <view class="form_item border_b" @click="show = true">
              <view class="label">服务标签：</view>

              <input
                v-if="!defaultSelected.length"
                class="inps"
                disabled
                placeholder="请选择服务标签"
              />
              <view v-else style="text-align: right; flex: 1">
                {{
                  defaultSelected
                    .map((item) => item.goods_category_title)
                    .join(',')
                }}
              </view>
              <uni-icons type="right" size="18"></uni-icons>
            </view>

            <view class="form_item border_b">
              <view class="label">服务地址：</view>
              <view class="flex" style="flex: 1">
                <input
                  v-if="!fromDttas.province_name"
                  class="inps"
                  disabled
                  placeholder="请选择服务地址"
                  @click="openNativeMap"
                />
                <view v-else>{{
                  `${fromDttas.province_name}${fromDttas.city_name}${fromDttas.district_name}${fromDttas.region_name}`
                }}</view>
                <view class="dw" @click="openNativeMap">
                  <uni-icons
                    type="location"
                    size="20"
                    color="#0291F6"
                  ></uni-icons>
                </view>
              </view>
            </view>

            <!-- <view class="form_item border_b">
              <view class="label">详细地址：</view>
              <input
                class="inps"
                v-model="fromDttas.address"
                type="text"
                placeholder="请输入详细地址"
              />
            </view> -->
            <view
              class="form_item border_b"
              style="
                flex-direction: column;
                align-items: flex-start;
                width: 100%;
              "
            >
              <view class="label">技能证书(最多五张)：</view>
              <view class="imgboxs">
                <view class="ulimgbox" v-if="imgList.length">
                  <view
                    class="lib"
                    v-for="(item, index) in imgList"
                    :key="index + 1"
                  >
                    <image :src="item" mode="aspectFill" />
                    <view class="close2" @click="imgList.splice(index, 1)">
                      <image
                        class="close2_img"
                        :src="`${store.imgDomain}close2.png`"
                        mode="scaleToFill"
                      />
                    </view>
                  </view>
                </view>

                <view
                  class="scb flex_center"
                  @click="chooseImage"
                  v-if="imgList.length < 5"
                >
                  <uni-icons
                    type="plusempty"
                    size="30"
                    color="#4D738D"
                  ></uni-icons>
                </view>
              </view>
            </view>
            <view class="form_item ac">
              <view class="label">自我介绍：</view>
              <textarea
                class="textareain"
                v-model="fromDttas.self_desc"
                type="text"
                placeholder="请输入自我介绍"
              />
            </view>
          </view>
        </view>
        <!-- 保存btn -->
        <view class="bottombox">
          <view class="btns" @click="doSaveWorkerApply">报名加入</view>
          <!-- 
          <label class="radio" @click="radiovalue = !radiovalue"
            ><radio
              style="transform: scale(0.8)"
              color="#007AF0"
              value="1"
              :checked="radiovalue"
            /><text
              >我已阅读并同意
              <text
                style="color: #16cbb9"
                @click.stop="
                  store.to(
                    '/pages/public/agreement?url=wxapp/login/getUserAgreement',
                  )
                "
                >《个人信息授权协议》</text
              >
            </text></label
          > -->
        </view>
      </template>

      <multiple-select
        v-model="show"
        :data="selectList2"
        label-name="goods_category_title"
        value-name="id"
        :default-selected="defaultSelected"
        @confirm="confirm"
      ></multiple-select>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, reactive } from 'vue';
import { useCounterStore } from '@/store';
import { onLaunch, onShow, onUnload } from '@dcloudio/uni-app';
import request from '@/utils/request';
import { validatePhone } from '@/utils/validate';
import multipleSelect from '@/components/momo-multipleSelect/momo-multipleSelect.vue';

const store = useCounterStore();
const userInfo = ref({});
const selectList = ref([]);
const selectList2 = ref([]);
const imgList = ref([]);
const radiovalue = ref(false);
const defaultSelected = ref([]);
const show = ref(false);
const avatarUrl = ref('');
// 参数
const fromDttas = reactive({
  region_name: '',
  worker_name: '',
  province_name: '',
  city_name: '',
  district_name: '',
  longitude: '',
  latitude: '',
  address: '',
  phone: '',
  self_desc: '',
  certificate_img: '',
  first_goods_category_id: '',
  second_goods_category_id_arr: '',
  headimg: '',
});

const type_title = computed(() => {
  if (fromDttas.first_goods_category_id) {
    const items = selectList.value.find(
      (i) => i.id === fromDttas.first_goods_category_id,
    );
    return items?.goods_category_title || '';
  }
  return '';
});
const bindPickerChange = (e) => {
  fromDttas.first_goods_category_id = selectList.value[e.detail.value].id;

  getSecondGoodsCategoryListByParentId(selectList.value[e.detail.value].id);
};

// 调起微信原生地图选择页面（自带搜索功能）
const openNativeMap = () => {
  // 检查位置权限（可选，提升体验）
  uni.getSetting({
    success: (settingRes) => {
      console.log('settingRes', settingRes);

      // 若未授权位置权限，先申请授权
      if (!settingRes.authSetting['scope.userLocation']) {
        uni.authorize({
          scope: 'scope.userLocation',
          success: (res) => {
            launchMap(); // 授权成功后调起地图
          },
          fail: () => {
            // 引导用户到设置页开启权限
            uni.showModal({
              title: '权限申请',
              content: '需要获取您的位置以显示附近地点，请开启位置权限',
              confirmText: '去设置',
              success: (modalRes) => {
                if (modalRes.confirm) {
                  uni.openSetting(); // 打开小程序设置页
                }
              },
            });
          },
        });
      } else {
        launchMap(); // 已授权，直接调起地图
      }
    },
  });
};

// 核心：调用 uni.chooseLocation 调起原生地图
const launchMap = () => {
  uni.chooseLocation({
    // 可选：设置地图初始中心位置（经纬度）
    // latitude: 39.9042, // 示例：北京纬度
    // longitude: 116.4074, // 示例：北京经度
    success: (res) => {
      getTencentMapAddress(res.latitude, res.longitude, res.name);
    },
    fail: (err) => {
      // 处理失败（如用户取消选择）
      if (err.errMsg !== 'chooseLocation:fail cancel') {
        uni.showToast({
          title: '地图选择失败',
          icon: 'none',
        });
      }
    },
  });
};
// 【腾讯地图】经纬度获取地信息
const getTencentMapAddress = async (latitude, longitude, name) => {
  const data = await request('wxapp/common/getTencentMapAddress', {
    location: `${latitude},${longitude}`,
  });
  fromDttas.longitude = longitude;
  fromDttas.latitude = latitude;
  fromDttas.province_name = data.ad_info.province;
  fromDttas.city_name = data.ad_info.city;
  fromDttas.district_name = data.ad_info.district;
  fromDttas.region_name = name;
};

// 上传图
const chooseImage = () => {
  uni.chooseImage({
    count: 5 - imgList.value.length,
    sourceType: ['album', 'camera'], // 可选择相册或相机（拍照）
    success: (res) => {
      res.tempFilePaths.forEach((tempFilePath) => {
        onChooseAvatar(tempFilePath); // 单独的单张上传函数
      });
    },
    fail: (err) => {
      console.log('选择图片失败', err);
    },
  });
};
// 选择头像回调
const onChooseAvatar = (tempFilePaths) => {
  uni.uploadFile({
    url: 'https://adm.jinjiangservice.com/index.php/wxapp/common/uploadCommonImage',
    method: 'POST',
    filePath: tempFilePaths.detail?.avatarUrl || tempFilePaths,
    formData: {
      file: tempFilePaths.detail?.avatarUrl || tempFilePaths,
    },
    header: {
      'Content-Type': 'multipart/form-data',
    },
    name: 'file',
    success(res) {
      if (tempFilePaths.detail?.avatarUrl) {
        fromDttas.headimg = JSON.parse(res.data).data.path;
      } else {
        imgList.value.push(JSON.parse(res.data).data.path);
      }
    },
  });
};
// 提交企业认证申请
const doSaveWorkerApply = async () => {
  fromDttas.certificate_img = imgList.value.join(',');
  fromDttas.second_goods_category_id_arr = defaultSelected.value
    .map((item) => item.id)
    .join(',');
  if (!fromDttas.headimg) {
    uni.showToast({
      title: '请选择头像',
      icon: 'none',
    });
    return;
  } else if (!fromDttas.worker_name) {
    uni.showToast({
      title: '请输入姓名',
      icon: 'none',
    });
    return;
  } else if (!validatePhone(fromDttas.phone)) {
    uni.showToast({
      title: '请输入正确的联系电话',
      icon: 'none',
    });
    return;
  } else if (!fromDttas.first_goods_category_id) {
    uni.showToast({
      title: '请选择服务类型',
      icon: 'none',
    });
    return;
  } else if (!fromDttas.second_goods_category_id_arr) {
    uni.showToast({
      title: '请选择服务标签',
      icon: 'none',
    });
    return;
  } else if (!fromDttas.province_name) {
    uni.showToast({
      title: '请选择服务地址',
      icon: 'none',
    });
    return;
  }
  await request('worker/login/doRegisterWorker', { ...fromDttas }, 'post');
  store.workerData.status = 1;
};
const confirm = (row) => {
  defaultSelected.value = [...row];
};

// 获取一级服务分类【师傅注册
const getFirstGoodsCategoryList = async () => {
  selectList.value = await request('worker/login/getFirstGoodsCategoryList');
};
// 根据给定一级服务分类获取所有二级服务分类
const getSecondGoodsCategoryListByParentId = async (
  first_goods_category_id,
  n,
) => {
  defaultSelected.value = [];
  fromDttas.second_goods_category_id_arr = '';
  selectList2.value = [];
  selectList2.value = await request(
    'worker/login/getSecondGoodsCategoryListByParentId',
    { first_goods_category_id },
  );
  if (n) {
    defaultSelected.value = [...store.workerData.second_goods_category_list];
  }
};

onShow(() => {
  console.log('收到的', store.phone);
  fromDttas.phone = store.phone;
  getFirstGoodsCategoryList();
  if (!store.workerData?.id) return;
  for (let key in fromDttas) {
    if (key != 'status') {
      fromDttas[key] = store.workerData[key];
    }
  }
  fromDttas.phone = '';
  imgList.value = fromDttas.certificate_img.split(',');
  getSecondGoodsCategoryListByParentId(fromDttas.first_goods_category_id, true);
});
</script>

<style lang="scss" scoped>
.page-container {
  background-color: #f8f8f8;
}
.topbars {
  background-color: #ffffff;
}
.page_content {
  position: relative;
  padding-bottom: 60rpx;
  .hztopimg {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
  }
  .forms {
    position: relative;
    z-index: 1;
    box-sizing: border-box;
    padding: 20rpx;
    margin-top: 312rpx;

    .formsbox {
      box-sizing: border-box;
      padding: 35rpx;
      background-color: #fff;
      border-radius: 20rpx;
      border: 1rpx solid #71cdc4;
      .titles {
        font-size: 36rpx;
        font-weight: 700;
        display: flex;
        align-items: center;
        image {
          margin-right: 20rpx;
          width: 38rpx;
          height: 38rpx;
        }
      }
      .form_item {
        display: flex;
        align-items: center;
        padding: 20rpx 0;
        font-size: 30rpx;
        &.ac {
          flex-direction: column;
          align-items: flex-start;
        }
        .inps {
          box-sizing: border-box;
          padding-left: 30rpx;
          flex: 1;
          text-align: right;
        }
        .select {
          display: flex;
          align-items: center;
          justify-content: space-between;
        }
      }
    }
  }
}
.ts {
  padding: 20rpx;
  box-sizing: border-box;
}
.bottombox {
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.btns {
  margin: 0 auto 20rpx;
  width: 90%;
  box-sizing: border-box;
  background-color: #14c6b5;
  line-height: 80rpx;
  font-size: 30rpx;
  color: #fff;
  text-align: center;
  border-radius: 40rpx;
}
.btnimg {
  width: 30%;
  line-height: 50rpx;
  text-align: center;
  color: #fff;
  font-size: 24rpx;
  background-color: #0086f2;
}
.imgsc {
  width: 200rpx;
  height: 200rpx;
  border-radius: 20rpx;
  border: 1rpx dashed #999;
}
.business_license_img {
  width: 200rpx;
  height: 200rpx;
  border-radius: 20rpx;
}
.jdlines {
  margin: 30rpx 0;
  justify-content: space-between;
  box-sizing: border-box;
  padding: 0 30rpx;
  .line {
    flex: 1;
    background-color: #dfdfdf;
    height: 1rpx;
  }
  .linredio {
    width: 29rpx;
    height: 29rpx;
    background-color: #fff;
    border-radius: 50%;
    border: 2rpx solid #d1d1d1;
    position: relative;
    text {
      position: absolute;
      left: 50%;
      bottom: -40rpx;
      white-space: nowrap;
      transform: translate(-50%);
      color: #999;
    }
    &::after {
      content: ' ';
      position: absolute;
      top: 50%;
      left: 50%;
      width: 16rpx;
      height: 16rpx;
      border-radius: 50%;
      background-color: #d1d1d1;
      transform: translate(-50%, -50%);
    }
    &.ac {
      border-color: #2ec3b5;
      text {
        color: #2ec3b5;
      }
      &::after {
        background-color: #2ec3b5;
      }
    }
  }
}

.ulimgbox {
  margin: 20rpx 0;
  display: flex;
  flex-wrap: wrap;

  .lib {
    width: 150rpx;
    margin-bottom: 20rpx;
    margin-right: 10rpx;
    display: flex;
    flex-direction: column;
    position: relative;
    .close2_img {
      position: absolute;
      top: -15rpx;
      right: -15rpx;
      width: 30rpx;
      height: 30rpx;
    }
    image {
      border-radius: 20rpx;
      width: 150rpx;
      height: 150rpx;
    }
  }
}
.scb {
  margin-top: 20rpx;
  border: 1rpx dashed #7cabd7;
  width: 150rpx;
  height: 150rpx;
  border-radius: 20rpx;
}
.imgboxs {
  width: 100%;
}
.dw {
  padding: 0 20rpx;
}
.label {
  flex-shrink: 0;
}
.textareain {
  width: 100%;
  border: 1rpx solid #999;
  border-radius: 10rpx;
  box-sizing: border-box;
  padding: 20rpx;
  margin-top: 20rpx;
}
.shbox {
  margin: 20rpx auto;
  width: 94%;
  background-color: #fff;
  box-sizing: border-box;
  padding: 20rpx;
  border-radius: 20rpx;
  flex-direction: column;
  border: 1rpx solid #71cdc4;
  .sh_img {
    width: 127rpx;
    height: 127rpx;
    margin-bottom: 35rpx;
  }
  .sh_text {
    font-size: 36rpx;
    font-weight: 600;
    margin-bottom: 35rpx;
  }
  .bm_text {
    width: 80%;
    margin-bottom: 50rpx;
  }
  .btns {
    background-color: #15cab9;
    width: 85%;
    line-height: 70rpx;
    border-radius: 35rpx;
    color: #fff;
    text-align: center;
  }
}
.btext {
  position: relative;
  margin-top: 35rpx;
  display: flex;
  justify-content: center;
  &::after {
    content: ' ';
    width: 100rpx;
    height: 1rpx;
    position: absolute;
    top: 50%;
    left: 140rpx;
    transform: translateY(-50%);
    background-color: #93dad3;
  }
  &::before {
    content: ' ';
    width: 100rpx;
    height: 1rpx;
    position: absolute;
    top: 50%;
    right: 140rpx;
    transform: translateY(-50%);
    background-color: #93dad3;
  }
  image {
    position: relative;
    display: block;
    opacity: 0.6;
    width: 185rpx;
    height: 38rpx;
  }
}
.wtf_box {
  border-radius: 20rpx;
  background: linear-gradient(to bottom, #f4fffd, #dbfffb);
  box-sizing: border-box;
  padding: 20rpx;
  flex-direction: column;
  margin-bottom: 20rpx;
  .qy_1_img {
    width: 44rpx;
    margin-right: 10rpx;
  }
  .t1 {
    font-size: 30rpx;
    font-weight: 700;
  }
}
.avatar-btn {
  flex: 1;
  margin: 0;
  margin-left: auto;
  font-size: 30rpx;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  width: max-content;
  background-color: transparent;
  outline: none;
  &::after {
    display: none;
  }
}
.avatar {
  width: 80rpx;
  height: 80rpx;
  margin-left: 20rpx;
  border-radius: 50%;
}
</style>
